package control;

import org.json.JSONException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;

import org.json.JSONArray;
import org.json.JSONObject;
import utils.DBconn;


public class userPageServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        response.setContentType("application/json; charset=utf-8");

        try {
            JSONArray array = tranJson();
            PrintWriter out = response.getWriter();
            out.write(array.toString());
            out.flush();
        } catch (SQLException | JSONException e) {
            e.printStackTrace();
        }


    }

    private JSONArray tranJson() throws SQLException, JSONException {
        DBconn.init();
        String sql = "select id, user_name, data from voicerobot.user_info ;";
        ResultSet  rs = DBconn.selectSql(sql);
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        JSONArray array = new JSONArray();
        while (rs.next()){
            JSONObject jsonObject = new JSONObject(new LinkedHashMap());
            for (int i = 1;i <= columnCount;i++){
                String columnName = metaData.getColumnLabel(i);
                String value = rs.getString(columnName);
                jsonObject.append(columnName,value);
            }
            array.put(jsonObject);
        }
        // System.out.println("转换json数据");
        // System.out.println("1111111111\n"+array.toString()+"\n");
        DBconn.closeConn();
        return array;
    }

}
